package com.snow.auth.controller;

import cn.hutool.core.bean.BeanUtil;
import com.snow.annotation.SysLog;
import com.snow.auth.component.AuthComponent;
import com.snow.conditions.ConditionType;
import com.snow.conditions.QueryConditionField;
import com.snow.jpa.LambdaQueryBuilder;
import com.snow.jpa.model.BasePageParams;
import com.snow.model.IdParams;
import com.snow.auth.entity.SystemDept;
import com.snow.auth.service.SystemDeptService;
import com.snow.view.IWebResponse;
import com.snow.view.PageData;
import com.snow.view.WebResponse;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.domain.Example;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 部门管理接口
 *
 * @author by 13119
 */
@RestController
@RequestMapping("/system-dept")
@AllArgsConstructor
public class SystemDeptController {

    private final AuthComponent authComponent;
    SystemDeptService systemDeptService;

    @Getter
    @Setter
    public static class CreateParams {
        @NotNull(message = "父菜单不能为空")
        private Integer parentId = 0;
        @NotNull(message = "部门名称不能为空")
        private String deptName;
        private Integer sort = 0;
    }

    @SysLog("创建部门")
    @PostMapping("/create")
    public IWebResponse create(@Validated @RequestBody CreateParams params) {
        if ((!params.getParentId().equals(0))) {
            Optional<SystemDept> optionalSystemDept = systemDeptService.getRepository().findById(params.getParentId());
            if (!optionalSystemDept.isPresent()) {
                return WebResponse.fail("父级部门不存在");
            }
        }
        SystemDept saveTemp = BeanUtil.copyProperties(params, SystemDept.class);
        saveTemp.setStatus(1);
        saveTemp.setCreateTime(new Date());
        return WebResponse.success(systemDeptService.save(saveTemp));
    }

    @SysLog("获取部门树")
    @RequestMapping("/tree")
    public IWebResponse tree() {
        return WebResponse.success(systemDeptService.tree());
    }

    @SysLog("删除部门")
    @PostMapping("/delete")
    public IWebResponse delete(@RequestBody IdParams params) {
        Optional<SystemDept> optionalSystemDept = systemDeptService.getRepository().findById(params.getId());
        if (!optionalSystemDept.isPresent()) {
            return WebResponse.fail("部门不存在");
        }
        SystemDept queryParams = new SystemDept();
        queryParams.setParentId(optionalSystemDept.get().getId());
        boolean existsChildren = systemDeptService.getRepository().exists(Example.of(queryParams));
        if (existsChildren) {
            return WebResponse.fail("存在子部门，无法删除");
        }
        return WebResponse.success(systemDeptService.delete(params.getId()));
    }


    @Getter
    @Setter
    public static class SearchParams extends BasePageParams {
        @QueryConditionField(type = ConditionType.like)
        private String deptName;
        @QueryConditionField(type = ConditionType.equal)
        private Integer tenantId;
    }

    @SysLog("分页查询部门")
    @PostMapping("/page")
    public WebResponse<PageData<SystemDept>> page(@Validated @RequestBody SearchParams params) {
        return WebResponse.success(systemDeptService.page(params));
    }

    @PostMapping("/search")
    public WebResponse<List<SystemDept>> search(@RequestBody SearchParams params) {
        // 如果未指定租户，那就筛选当前租户
        if (params.getTenantId() == null) {
            params.setTenantId(authComponent.getCurrentUser().getTenantId());
        }
        LambdaQueryBuilder.disableTenantFilter();
        return WebResponse.success(systemDeptService.search(params));
    }

    @PostMapping("/update")
    public WebResponse<Void> update(@RequestBody SystemDept params) {
        systemDeptService.update(params);
        return WebResponse.success();
    }

}
